package com.health.crm.sys.filter;

import com.health.core.constant.CommonConstants;
import com.health.core.constant.ServiceConstants;
import com.health.core.support.HealthThreadLocal;
import com.health.core.util.AppJwtUtil;
import com.health.core.util.GeneralUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = {ServiceConstants.HEALTH_FILE_MEASURE_URL_PR + "/*",
        "/hfm" + ServiceConstants.HEALTH_FILE_MEASURE_URL_PR + "/*"},filterName = "accessFilter")
public class AccessFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json");
        String gatewayKey = request.getHeader("gatewayKey");
        String keyEncrypt = request.getHeader("keyEncrypt");
        HealthThreadLocal.setDataSourceKey(StringUtils.isNotBlank(request.getHeader("enterprise")) ? request.getHeader("enterprise") : "");
        if (StringUtils.isBlank(gatewayKey) && StringUtils.isBlank(keyEncrypt)) {
            response.getWriter().write("请通过网关访问");
        } else {
            if (GeneralUtil.decrypt(CommonConstants.ENCRYPTED, keyEncrypt).equals(gatewayKey)) {
                verifyToken(request, response, filterChain);
            } else {
                response.getWriter().write("非法请求");
            }
        }
    }


    private boolean checkout(HttpServletRequest request) {
        boolean flag = false;
        return true;
    }

    // 网关应只管生成token 校验则在具体的服务
    private void verifyToken(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            response.getWriter().write("非法请求");
        } else {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            filterChain.doFilter(request, response);
        }
    }

}
